/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 *
 * The Initial Developer of the Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 * Portions created by Mark A. Kobold are Copyright (C) 2000-2007. All Rights Reserved.
 *
 * Contributor(s): 
 *  Mark A. Kobold [mkobold <at> isqlviewer <dot> com].
 *  
 * If you didn't download this code from the following link, you should check
 * if you aren't using an obsolete version: http://www.isqlviewer.com
 */
package org.isqlviewer.ui.listeners;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.TreePath;

import org.isqlviewer.model.JdbcSchemaTreeModel;
import org.isqlviewer.model.SchemaNode;
import org.isqlviewer.sql.ResultSetRenderer;
import org.isqlviewer.swing.action.SwingEventManager;
import org.isqlviewer.ui.dnd.SchemaNodeRenderer;
import org.isqlviewer.util.LoggableObject;

/**
 * Object for handling expansion and selection events from a JDBC Schema tree model.
 * <p>
 * This class is mainly responsible for the lazy loading effect since a JDBC schema can be quite large we wou
 * realistically only want to load the stuff on demand.
 * 
 * @author Mark A. Kobold &lt;mkobold at isqlviewer dot com&gt;
 * @version 1.0
 */
public class SchemaTreeListener extends LoggableObject implements MouseListener, TreeExpansionListener {

    private JdbcSchemaTreeModel jdbcSchema = null;
    private SwingEventManager eventManager = null;
    private ResultSetRenderer renderer = null;
    private AtomicBoolean treeExpansionLock = new AtomicBoolean(false);

    public SchemaTreeListener(JdbcSchemaTreeModel jdbcSchema, ResultSetRenderer renderer, SwingEventManager eventManager) {

        this.jdbcSchema = jdbcSchema;
        this.eventManager = eventManager;
        this.renderer = renderer;
    }

    public void treeExpanded(TreeExpansionEvent event) {

        SchemaNode node = (SchemaNode) event.getPath().getLastPathComponent();
        if (node.isNoncached()) {
            eventManager.enqueueRunnable(new SchemaNodeExpander(this, event));
        }

    }

    public void treeCollapsed(TreeExpansionEvent event) {

    }

    public void mouseClicked(MouseEvent e) {

        handleInput(e);
    }

    public void mousePressed(MouseEvent e) {

        // handleInput(e);
    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

    private void handleInput(MouseEvent e) {

        int clickCount = e.getClickCount();
        if (clickCount == 2 && !e.isPopupTrigger()) {
            if (!treeExpansionLock.get()) {
                JTree tree = (JTree) e.getSource();
                TreePath path = tree.getSelectionPath();
                SchemaNode node = (SchemaNode) path.getLastPathComponent();
                Runnable runnable = new SchemaNodeRenderer(renderer, jdbcSchema, tree, node);
                eventManager.enqueueRunnable(runnable);
            }
        }
    }

    private static class SchemaNodeExpander implements Runnable {

        private TreeExpansionEvent event = null;
        private JdbcSchemaTreeModel jdbcSchema = null;
        private AtomicBoolean lock = null;

        public SchemaNodeExpander(SchemaTreeListener ownerReference, TreeExpansionEvent event) {

            this.jdbcSchema = ownerReference.jdbcSchema;
            this.event = event;
            this.lock = ownerReference.treeExpansionLock;
        }

        public void run() {

            if (event == null) {
                return;
            }
            synchronized (lock) {
                lock.set(true);
            }
            boolean cursorSet = false;
            Component owner = null;
            try {
                owner = SwingUtilities.getAncestorOfClass(JScrollPane.class, (Component) event.getSource());
                owner.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                cursorSet = true;
            } catch (Exception ignored) {

            }
            try {
                SchemaNode node = (SchemaNode) event.getPath().getLastPathComponent();
                jdbcSchema.loadChildNodes(node);
            } finally {
                if (cursorSet && owner != null) {
                    owner.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
                synchronized (lock) {
                    lock.set(false);
                }
                if (owner != null) {
                    owner.invalidate();
                }
            }
        }
    }

}
